<template>
  <div v-loading="loading" :element-loading-text="elementLoadingText">
    <div class="uploadBody">
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        class="dataForm"
      >
        <!-- 非文档库页面上传界面 -->
        <el-row v-if="isShowFileType">
          <el-col :span="24">
            <el-form-item :hidden="hiddenTypeFlag" :label="$t('文件分类')" prop="classify">
              <el-select
                ref="classifySelect"
                v-model="form.classifyName"
                filterable
                clearable
                :placeholder="$t('请选择或输入文字检索')"
                :filter-method="filterMethod"
                @clear="filterMethod"
                @visible-change="visibleChange"
              >
                <div slot="empty" v-loading="selectLoading" style="height: 275px;overflow: auto;padding: 10px 0;font-size: 14px;">
                  <el-tree
                    ref="treeSelect_myself"
                    :data="fileDirOptions"
                    :load="loadNode"
                    :expand-on-click-node="false"
                    :lazy="true"
                    :default-expanded-keys="expansionLevel"
                    node-key="id"
                    :props="props"
                    height="100%"
                    @node-click="handleNodeClick"
                  >
                    <span slot-scope="{ node, data }" class="custom-tree-node">
                      <span :id="data.id" :class="[data.isDisabled ? 'disableChoose' : '']">
                        {{ node.label }}
                      </span>
                    </span>
                  </el-tree>
                </div>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('文件上传')" :rules="[{ required: true}]" />
          </el-col>
        </el-row>
        <!-- <div>
          <span><i style="color: rgb(255, 73, 73); margin-right: 4px;">*</i>
            {{ $t('文件上传') }}
          </span>
        </div> -->

        <!-- 上传 -->
        <uploader
          ref="uploader"
          :options="options"
          :auto-start="false"
          class="uploader-app"
          :file-status-text="statusText"
          @files-added="onFilesAdded"
          @file-success="onFileSuccess"
          @file-progress="onFileProgress"
          @file-error="fileError"
          @complete="complete"
          @dragover="dragoverStatus = true"
          @dragleave="dragoverStatus = false"
          @drop="dragoverStatus = false"
        >
          <uploader-btn id="global-uploader-btn" ref="uploadBtn" class="choice-file-btn" :attrs="attrs">
            <el-link :underline="false" type="primary">{{ $t("本地上传") }}</el-link>
          </uploader-btn>
          <!--//可拖拽的区域-->
          <uploader-drop class="drop" style="padding: 0;">
            <uploader-list>
              <div slot-scope="props" class="file-panel" :style="{ 'box-shadow': (dragoverStatus ? '#b0b0b0 2px 0px 3px 0px' : '') }">
                <ul class="file-list">
                  <li v-for="file in props.fileList" :key="file.id">
                    <uploader-file ref="files" :class="'file_' + file.id" :file="file" :list="true" />
                  </li>
                  <div v-if="!props.fileList.length" class="no-file">
                    {{ $t('拖拽文件到此处进行上传') }}
                    <i class="el-icon-upload" />
                  </div>
                </ul>
              </div>
            </uploader-list>
          </uploader-drop>
          <div v-if="true" class="choice-file-btn">
            <el-link :underline="false" type="primary" @click="openFolderPageMethod">{{ $t("从文档库选择") }}</el-link>
          </div>
          <div v-if="true" class="uploader-list choice-file">
            <ul class="file-list">
              <li v-for="(file, index) in selectChoiceFiles" :key="index">
                <div status="success" class="uploader-file">
                  <div class="uploader-file-progress" style="transform: translateX(0%);" />
                  <div class="uploader-file-info">
                    <div class="uploader-file-name"><i icon="image" class="uploader-file-icon" />{{ file.name }}</div> <div class="uploader-file-size">{{ file.size }}</div>
                    <div class="uploader-file-status">
                      <span>{{ $t('选择成功') }}</span>
                    </div>
                    <div class="uploader-file-actions">
                      <span class="uploader-file-remove" @click="delFile(file, index)" />
                    </div>
                  </div>
                </div>
              </li>
              <div v-if="!selectChoiceFiles.length" class="no-file">{{ $t('暂无选择文件') }}</div>
            </ul>
          </div>
        </uploader>
        <el-row>
          <!-- 项目基金选择 -->
          <span v-show="false">
            条件: ({{ mainBodyVueShow && (businessId !== 'other' || businessType !== '') && selectBusinessData === true }}) <br>
            mainBodyVueShow: ({{ mainBodyVueShow }} <br>
            businessId: ({{ businessId }}) <br>
            selectBusType:  ({{ selectBusType }}) <br>
            selectBusinessData: {{ selectBusinessData }}<br>
            mainBodySelectValue: ({{ mainBodySelectValue }}) <br>
            mainBodyChoice: ({{ mainBodyChoice }}) <br>
          </span>
          <el-col v-if="mainBodyVueShow && (businessId !== 'other' || businessType !== '') && selectBusinessData === true" :span="24">
            <el-form-item prop="mainBody">
              <div v-if="mainBodyChoice === 'spv'">
                <i style="color: #ff4949;margin-right: 4px;">*</i>
                <span style="font-weight: bold;">{{ $t('SPV') }}</span>
              </div>
              <MainBodySelect
                v-if="mainBodyChoice !== 'company_portal_file'"
                v-model="mainBodySelectValue"
                :parameters="mainBodyChoice"
                :show-label="mainBodyChoice !== 'spv'"
                :select-bus-type="selectBusType"
                :disabled="mainBodyDisabled"
                :scope-authority="true"
                style="width: 100%"
                @change="schange(mainBodySelectValue)"
              />
              <div v-if="mainBodyChoice === 'company_portal_file'">
                <span slot="label">
                  <i style="color: #ff4949;margin-right: 4px;">*</i>
                  <span style="font-weight: bold;">{{ $t('企业名称') }}</span>
                </span>
                <el-select
                  v-model="mainBodySelectValue"
                  :placeholder="$t('请选择')"
                  filterable
                  clearable
                >
                  <el-option
                    v-for="dict in companyPortalFileOption"
                    :key="dict.dictValue"
                    :label="$t(dict.dictLabel)"
                    :value="dict.dictValue"
                  />
                </el-select>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 出资人下拉 -->
        <el-row v-if="parentFolder.belong === 'data_room' && !isEmpty(mainBodySelectValue)">
          <el-col :span="24">
            <el-form-item :label="$t('可见出资人')" prop="lpIdList">
              <span slot="label">
                {{ $t('可见出资人') }}
                <el-tooltip :content="$t('可查看文档的出资人')" placement="top">
                  <i class="el-icon-question" />
                </el-tooltip>
              </span>
              <el-select v-model="form.lpIdList" filterable clearable multiple collapse-tags>
                <el-option
                  v-for="item in lpListOptions"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="isShowFileType">
          <el-col v-if="showType === 'normal'" :span="24">
            <el-form-item :label="$t('备注')" prop="remark">
              <el-input v-model="form.remark" type="textarea" :autosize="{ minRows: 3, maxRows: 10}" maxlength="500" show-word-limit :placeholder="$t('备注')" />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 提醒用户 -->
        <el-row v-if="remindUserStatus">
          <el-col :span="24">
            <el-form-item :label="$t('提醒用户')" prop="remindUsers">
              <UserSelect
                v-model="form.remindUsers"
                :multiple="true"
                :placeholder="this.$t('选择用户')"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <el-button @click="cancel">{{ $t("取消") }}</el-button>
      <el-button type="primary" :disabled="disabledSave || fileList.length <= 0" @click="sendData">{{ $t("保存") }}</el-button>
    </div>

    <el-dialog v-if="openFolderPage" :title="$t('文档库')" :visible.sync="openFolderPage" :close-on-click-modal="false" custom-class="folderOpen" :lock-scroll="false" append-to-body>
      <folderFastChioce ref="folderFastChioce" :un-upload-sub-win-open="false" @uploadChoiceToParent="uploadChoiceToParent" />
    </el-dialog>
  </div>
</template>

<script>
    import $ from 'jquery'
    import SparkMD5 from 'spark-md5'
    import jsMd5 from 'js-md5'
    import MainBodySelect from '@/components/MainBodySelect/index'
    import folderFastChioce from '@/views/folder/index.vue'
    import '@riophae/vue-treeselect/dist/vue-treeselect.css'
    import { ACCEPT_CONFIG } from '@/utils/config'
    import { config } from '@/utils'
    import { getToken } from '@/utils/auth'
    import { getLpView } from '@/api/base/deal/dealBase'
    import {
      fileClassTreeStructure,
      fileClassTreeStructureSearch,
      findListByIdNotPer,
      checkFolderPermission
    } from '@/api/file/filefolder/folder.js'
    import { fileBaseMerging, getVarParam } from '@/api/file/fileBase'
    import { listDealTypeCompanySelect } from '@/api/company/base/companyBase'
    import { getArrayByCode } from '@/api/file/directoryRelatedBusiness/directoryRelatedBusiness'
    import { getFileConfigByCode } from '@/api/file/fileConfig/fileConfig'
    import { listDict } from '@/api/fund/investor/fundInvestor'
    export default {
      components: {
        MainBodySelect,
        folderFastChioce
      },
      props: {
        dataType: {
          type: String,
          default: () => ''
        },
        // 是否展示文件分类 维度展示按钮(主要区分是在业务页面 还是在文档库)
        isShowFileType: {
          type: Boolean,
          default: () => true
        },
        // 是否展示选择项目, 基金...的下拉
        mainBodyVueShow: {
          type: Boolean,
          default: () => true
        },
        businessId: {
          type: String,
          default: () => ''
        },
        // 当businessType有值时. businessId失效. 将不会更具这个Id列出目录
        businessType: {
          type: String,
          default: () => ''
        },
        // 文档库如果上传按钮点击后打开页面存在文件分类 (前提 -> isShowFileType: true, 且businessId: undefined 必须) 当前才能生效
        uploadBusinessType: {
          type: String,
          default: () => ''
        },
        fileId: {
          type: String,
          default: () => ''
        },
        // 展示类型
        showType: {
          type: String,
          default: 'normal'
        },
        // 如果选择了特定的业务类型，是否需要选择业务数据
        selectBusinessData: {
          type: Boolean,
          default: true
        },
        // 是否隐藏提醒用户
        remindUserStatus: {
          type: Boolean,
          default: true
        },
        // 指定文件后缀
        specifyFileSuffix: {
          type: Array,
          default: undefined
        },
        // 指定文件大小(单位MB)
        specifyFileSize: {
          type: Number,
          default: undefined
        },
        hiddenTypeFlag: {
          type: Boolean,
          default: false
        }
      },
      data() {
        return {
          mainBodySelectValue: this.autoBusinessId(this.$route.query.lpId === undefined ? this.$route.query.id : this.$route.query.lpId, this.getParentForm()),
          // mainBodySelect 组件中展示, 项目还是基金....
          mainBodyChoice: undefined,
          selectBusType: '',
          // mainbody是否禁用
          mainBodyDisabled: false,
          loading: false,
          form: {
            classify: null,
            remark: '',
            remindUsers: ''
          },
          fileDirOptions: [],
          // 下拉检索延时变量
          searchTimer: undefined,
          // 当前下拉的搜索belong条件
          currentBelong: undefined,
          statusText: {
            success: this.$t('上传成功'),
            error: this.$t('上传失败'),
            uploading: this.$t('上传中'),
            paused: this.$t('上传暂停'),
            waiting: this.$t('等待上传')
          },
          // 选中的文件
          selectChoiceFiles: [],
          // 选中的来自文档库的原来对象
          selectFolderFiles: [],
          rules: {},
          // 记录分块都上传了那些快. 针对丢失的块进行重传操作
          uploadedInfo: [],
          // 是否正拖拽着文件
          dragoverStatus: false,
          options: {
            target: config.baseURL + '/file/fileBase/uploadDocLib?dataType=' + this.dataType + '&fileId=' + this.fileId,
            singleFile: false,
            chunkSize: '2048000',
            fileParameterName: 'file',
            maxChunkRetries: 3,
            testChunks: true, // 是否开启服务器分片校验
            // 服务器分片校验函数，秒传及断点续传基础
            checkChunkUploadedByResponse: function(chunk, message) {
              const objMessage = JSON.parse(message)
              if (objMessage.data !== null && objMessage.data.numbers !== null) {
                return (JSON.parse(objMessage.data.numbers) || []).indexOf(chunk.offset + 1) >= 0
              } else {
                return false
              }
            },
            headers: {
              Authorization: getToken()
            },
            query() {}
          },
          attrs: {
            accept: ACCEPT_CONFIG.getAll()
          },
          disabledSave: true,
          fileList: [],
          // 后台配置文件参数
          backgroundProfileParame: undefined,
          // 下拉菜单展开的ID集合
          expansionLevel: [],
          elementLoadingText: 'loading...',
          // 文档库对应的文件夹Id
          folderId: '',
          folderName: '',
          // 标的专用select OPtion
          companyPortalFileOption: [],
          // 防重复
          queryCount: 0,
          // 关联关系
          vueUploadCurrDeptChange: [],
          // 获取默认目录配置. 解决updated重复调用问题
          dataTypeDefaultCount: 0,
          // 点击的那个目录的上传
          parentFolder: {},
          // dataRoom页面需要展示出资人下拉
          lpListOptions: [],
          /*   *   * 选择文档库属性 start *    *   */
          openFolderPage: false,
          /*   *   * 选择文档库属性  end  *    *   */
          props: {
            children: 'children',
            label: 'label',
            disabled: 'isDisabled'
          },
          selectLoading: false
        }
      },
      computed: {
        // Uploader实例
        uploader() {
          return this.$refs.uploader.uploader
        }
      },
      watch: {
        businessId: {
          handler(val) {
            if (val !== '' && val !== undefined) {
              this.mainBodySelectValue = this.businessId
            }
            this.directorySwitch()
          },
          deep: true,
          immediate: true
        },
        mainBodyChoice: {
          handler(val) {
            if (val === 'company_portal_file') {
              this.companyPortalFileOption = []
              listDealTypeCompanySelect({}).then(response => {
                response.rows.forEach(item => {
                  this.companyPortalFileOption.push({ dictLabel: item.companyName, dictValue: item.id })
                })
              })
            }
          }
        }
      },
      mounted() {
        if (this.$refs.uploader?.assignDrop !== undefined) {
          this.$refs.uploader.assignDrop(document.getElementById('dropTarget'))
        }
      },
      created: function() {
        // 后台配置文件参数
        getVarParam().then(response => {
          this.backgroundProfileParame = undefined
          var suffix = response.data.document.toString() + ',' +
            response.data.image.toString() + ',' +
            response.data.media.toString() + ',' +
            response.data.text.toString()
          try {
            // 转大小写
            suffix = suffix.toLocaleUpperCase() + ',' + suffix.toLocaleLowerCase()
          } catch (e) {
            console.error(e)
          }
          this.backgroundProfileParame = { suffix: suffix, maxFileSize: response.data.maxFileSize[0] }
          if (suffix && !this.isEmpty(suffix)) {
            this.attrs.accept = []
            var tempSuffix = []
            suffix.split(',').forEach(item => {
              tempSuffix.push('.' + item)
            })
            this.attrs.accept = tempSuffix.join(',')
            this.$refs.uploadBtn.$el.querySelectorAll('input')[0].accept = tempSuffix.join(',')
          } else {
            this.attrs.accept = ACCEPT_CONFIG.getAll()
          }
        })
        if (!this.hiddenTypeFlag) {
          this.rules.classify = [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
        }
        // 日志输出
        console.info('upload:当前业务ID: ' + this.mainBodySelectValue, '为空时表示不在项目. 或基金...中')
        var thisPageBusinessId = this.autoBusinessId(this.$route.query.lpId === undefined ? this.$route.query.id : this.$route.query.lpId, this.getParentForm())
        if (thisPageBusinessId === undefined) {
          this.mainBodyDisabled = false
        } else {
          this.mainBodyDisabled = true
        }

        // 默认流程节点文档分类
        getFileConfigByCode('file_node_' + this.dataType, 'LCJD').then(response => {
          console.log(response)
          // 项目组同事根据自己那边的情况去找到nodeId就行
          var nodeId = ''
          if (this.$parent.$parent.$parent.$parent.$parent.$parent.$parent) {
            if (this.$parent.$parent.$parent.$parent.$parent.$parent.$parent.currentChildNode) {
              nodeId = this.$parent.$parent.$parent.$parent.$parent.$parent.$parent.currentChildNode.id
            }
          }
          if (!this.isEmpty(nodeId)) {
            // 选中默认配置
            this.form.classify = response.data.documentType
          }
        })

        this.findListCurrDeptChange()
      },
      updated() {
        if (this.dataType && this.dataTypeDefaultCount === 0) {
          // 根据标识获取
          getFileConfigByCode('file_select_' + this.dataType, 'MRFL').then(response => {
            if (response.data !== null && response.data.documentType !== null && response.data.documentType !== '' && response.data.documentType !== undefined) {
              const ids = JSON.parse(response.data.documentType)
              findListByIdNotPer({ dirIdList: ids }).then(response => {
                this.fileDirOptions = response.data
                this.checkIfItIsOptionalMain(this.fileDirOptions)
              })
            }
          })
          this.dataTypeDefaultCount++
        }
      },
      methods: {
        init() {
          this.form = {
            classify: null,
            remark: '',
            remindUsers: ''
          }
          this.fileList = []
          this.selectChoiceFiles = []
          this.selectFolderFiles = []
          if (this.isShowFileType) {
            // 加载表单 下拉内容
            if (this.businessId !== '' && this.businessId !== undefined) {
              this.mainBodySelectValue = this.businessId
            }
            this.directorySwitch()
          }
        },
        /**
         * 下拉隐藏事件
         */
        visibleChange(status) {
          if (!status && this.isEmpty(this.form.classify)) {
            this.filterMethod('')
          }
        },
        /**
         * 下拉检索事件
         */
        filterMethod(value) {
          if (!this.isEmpty(value)) {
            this.selectLoading = true
            clearInterval(this.searchTimer)
            this.searchTimer = setInterval(() => {
              // 关闭懒加载
              this.$refs.treeSelect_myself.$data.store.lazy = false
              // 全部展开
              this.$refs.treeSelect_myself.$data.store.defaultExpandAll = true
              // 检索关键字
              fileClassTreeStructureSearch({ name: value, belong: this.currentBelong, businessId: this.mainBodySelectValue }).then(response => {
                if (!this.isEmpty(response.data)) {
                  this.fileDirOptions = response.data
                } else {
                  this.fileDirOptions = []
                }
                this.checkIfItIsOptionalMain(this.fileDirOptions)
                this.selectLoading = false
              }).catch(() => {
                this.selectLoading = false
              })
              // 事件触发后,清除定时器
              clearInterval(this.searchTimer)
            }, 1000)
          } else {
            // 关闭懒加载
            this.$refs.treeSelect_myself.$data.store.lazy = true
            // 全部展开
            this.$refs.treeSelect_myself.$data.store.defaultExpandAll = false
            // 重新检索
            this.selectLoading = true
            fileClassTreeStructure({ businessId: this.mainBodySelectValue, belong: this.currentBelong, parentId: '0' }).then(response => {
              this.fileDirOptions = response.data
              this.checkIfItIsOptionalMain(this.fileDirOptions)
              this.selectLoading = false
            }).catch(() => {
              this.selectLoading = false
            })
          }
        },
        /**
         * 选中下拉事件, 赋值的
         */
        handleNodeClick(data) {
          if (data.isDisabled === false) {
            this.$set(this.form, 'classify', data.id)
            this.$set(this.form, 'classifyName', data.label)
            this.$refs.classifySelect.blur()
            this.currDeptChange(data)
          } else {
            this.msgError('该目录不可选择')
            this.expansionLevel.push(data.id)
          }
          // 选中后判断项目/基金..是否有对当前选中的目录有权限
          this.checkFolderPermission()
        },
        /**
         * 懒加载方法
         */
        loadNode(node, resolve) {
          fileClassTreeStructure({ businessId: this.mainBodySelectValue, belong: node.data.belong, parentId: node.data.id }).then(response => {
            var data = response.data
            this.checkIfItIsOptionalMain(data)
            console.log(node, response)
            resolve(data)
          })
        },
        /** 选中后判断项目,基金..是否有对当前选中的目录有权限 **/
        checkFolderPermission() {
          console.log('校验权限')
          if (this.isShowFileType) {
            this.checkFolderPermissionSub(this.form.classify, this.mainBodySelectValue)
          } else {
            this.checkFolderPermissionSub(this.parentFolder.id, this.mainBodySelectValue)
          }
        },
        checkFolderPermissionSub(folderId, businessId) {
          if (!this.isEmpty(folderId) && !this.isEmpty(businessId)) {
            checkFolderPermission(folderId, businessId).then(response => {
              if (response.msg === 'N') {
                var temp = ''
                if (!this.isEmpty(this.form.classifyName)) {
                  temp = '[' + this.form.classifyName + ']'
                }
                this.msgWarning(this.$t('项目') + temp + this.$t('无上传权限'))
                this.mainBodySelectValue = undefined
              }
            })
          }
        },
        // 取消按钮
        cancel() {
          this.$set(this.$refs.uploader, 'fileList', [])
          this.$set(this.$refs.uploader.uploader, 'fileList', [])
          this.$parent.$parent.uploaderOpen = false
          if (this.$parent.$parent.$parent.uploaderOpen) {
            this.$parent.$parent.$parent.uploaderOpen = false
          }
        },
        async findListCurrDeptChange() {
          await getArrayByCode('vueUpload_currDeptChange').then(response => {
            this.vueUploadCurrDeptChange = response.data
          })
        },
        // 多个文件的校验
        onFilesAdded(files, fileList) {
          console.log(files, fileList)
          this.disabledSave = true
          try {
            var isHaveFolder = false
            files.forEach((file) => {
              if (['.DS_Store'].includes(file.name)) {
                file.cancel()
              } else {
                if (this.checkUpload(file)) {
                  this.statusSet(file.id, 'md5')
                  this.computeMD5(file)
                } else {
                  file.error = true
                  file.cancel()
                }
              }
            })
            this.saveBtnStatus()
            if (isHaveFolder) {
              this.msgError(this.$t('暂不支持上传目录'))
            }
          } catch (e) {
            console.error(this.$t('文件上传校验大小, 以及文件类型异常!'), e)
          }
        },
        checkUpload(file) {
          var size
          try {
            size = parseInt(this.backgroundProfileParame.maxFileSize)
          } catch (e) {
            size = 200
            console.error(this.$t('环境变量配置异常!'), e)
          }
          // 根据组件指定上传文件大小
          if (this.specifyFileSize !== undefined && this.specifyFileSize !== null && !isNaN(this.specifyFileSize)) {
            size = this.specifyFileSize
          }
          var suffix = this.backgroundProfileParame.suffix
          // 根据组件指定文件后缀上传
          if (this.specifyFileSuffix !== undefined && this.specifyFileSuffix !== null && this.specifyFileSuffix !== '') {
            suffix = this.specifyFileSuffix
          }
          var item = file
          // 文件大小
          if (item.size >= 1024 * 1024 * size) {
            this.msgError(this.$t('[' + file.name + ']: 请上传小于') + size + 'MB' + this.$t('文件'))
            return false
          }
          if (item.size <= 0) {
            this.msgError(this.$t('不能上传空文件'))
            return false
          }
          // 文件类型
          const fileSuffix = item.name.substr(item.name.lastIndexOf('.') + 1, item.name.length)
          if (suffix.indexOf(fileSuffix.toLowerCase()) === -1) {
            this.msgError(this.$t('[' + file.name + ']: 暂不支持上传该类型!'))
            return false
          }
          return true
        },
        // 上传中
        onFileProgress() {
          this.disabledSave = true
          this.saveBtnStatus()
        },
        onFileSuccess(rootFile, file, response) {
          if (rootFile.isFolder) {
            console.log('上传的目录')
            this.$refs.uploader.fileList && this.$refs.uploader.fileList.forEach((item, index) => {
              if (item.name === rootFile.name) {
                this.$refs.uploader.fileList.splice(index, 1)
              }
            })
            this.$refs.uploader.fileList.push(file)
          }
          const res = JSON.parse(response)
          if (res.data !== null) {
            // console.log(file.name + '文件上传阶段: ' + res.data.status + ',该文件存在的块数有: ' + JSON.parse(res.data.numbers))
            // 判断块是否全了. 不全的话重新上传
            if (JSON.parse(res.data.numbers).length === file.chunks.length) {
              this.callbackMerge(file)
            } else {
              console.log(file.name + '文件上传阶段: ' + res.data.status + ',该文件存在的块数有: ' + JSON.parse(res.data.numbers))
              file.bootstrap()
              file.retry()
            }
          } else {
            // 发生未知错误, 清理列表. (较大可能存在的原因:不同用户, 同一时间上传了MD5相同的附件)
            rootFile.clean()
          }
        },
        /**
         * 回调合并, 调用后台接口, 使其合并该文件
         * @param file
         */
        callbackMerge(file) {
          // 分段全了. 反馈给后台, 让文件进行合并
          this.statusSet(file.id, 'merging')
          // 调用后台, 处理文件合并
          fileBaseMerging({
            identifier: file.uniqueIdentifier,
            dataType: this.dataType,
            totalSize: file.size,
            originalFilename: file.name,
            totalChunks: file.chunks.length,
            fileId: this.fileId
          }).then(response => {
            // 当前文件全部上传完成
            this.$bus.$emit('fileSuccess')
            if (!(this.fileList instanceof Array)) {
              this.$set(this, 'fileList', [])
            }
            this.fileList = this.uploader.fileList
            // 附加从文档库选择的附件
            this.selectChoiceFiles && this.selectChoiceFiles.forEach(item => {
              if (!(this.fileList instanceof Array)) {
                this.$set(this, 'fileList', [])
              }
              this.fileList.push(item)
            })
            // 设置文件的ID
            file.id = response.data.fileId
            // console.log('上传结果:', response.data)
          }).catch(e => {
            console.error('文件合并回调失败!', e)
            this.statusSet(file.id, 'failed')
          })
        },
        // 上传完毕
        complete() {
          this.saveBtnStatus()
        },
        fileError(rootFile, file, response) {
          this.saveBtnStatus()
          this.$message({ message: response, type: 'error' })
        },
        /**
         * 计算md5，实现断点续传及秒传
         * @param file
         */
        computeMD5(file) {
          const fileReader = new FileReader()
          // const time = new Date().getTime()
          const blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice
          let currentChunk = 0 // 当前分片
          const chunkSize = 10 * 1024 * 1000
          const chunks = Math.ceil(file.size / chunkSize) // 计算该文件一共有多少个分片
          const spark = new SparkMD5.ArrayBuffer() // 创建一个spark md5计算arrayBuffer的对象
          // 文件状态设为"计算MD5"
          this.statusSet(file.id, 'md5')
          file.pause()
          loadNext() // 首次读取文件分片
          // debugger
          // 当前分片读取完成
          fileReader.onload = e => {
            // debugger
            spark.append(e.target.result)
            if (currentChunk < chunks) {
              currentChunk++
              loadNext()
              // 实时展示MD5的计算进度
              this.$nextTick(() => {
                $(`.myStatus_${file.id}`).text('校验MD5 ' + ((currentChunk / chunks) * 100).toFixed(0) + '%')
              })
            } else {
              // 最后一个分片，结束
              const md5 = spark.end() + '_' + jsMd5(file.name)
              this.computeMD5Success(md5, file)
            }
          }
          fileReader.onerror = function() {
            this.error(this.$t('文件读取出错，请检查文件'))
            file.cancel()
          }
          function loadNext() { // 读取文件分片
            const start = currentChunk * chunkSize // 切片起始位置
            const end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize // 切片终止位置
            fileReader.readAsArrayBuffer(blobSlice.call(file.file, start, end)) // fileReader读取下一个文件分片
          }
        },
        computeMD5Success(md5, file) {
          // 将自定义参数直接加载uploader实例的opts上
          Object.assign(this.uploader.opts, {
            query: {
              ...this.params
            }
          })
          file.uniqueIdentifier = md5
          file.resume()
          this.statusRemove(file.id)
        },
        /**
         * 新增的自定义的状态: 'md5'、'transcoding'、'failed'
         * @param id
         * @param status
         */
        statusSet(id, status) {
          const statusMap = {
            md5: {
              text: this.$t('校验MD5'),
              bgc: '#fff'
            },
            merging: {
              text: this.$t('合并中'),
              bgc: '#e2eeff'
            },
            transcoding: {
              text: this.$t('转码中'),
              bgc: '#e2eeff'
            },
            failed: {
              text: this.$t('上传失败'),
              bgc: '#e2eeff'
            }
          }
          this.$nextTick(() => {
            $(`<p class="myStatus_${id}"></p>`).appendTo(`.file_${id} .uploader-file-status`).css({
              'position': 'absolute',
              'top': '0',
              'left': '0',
              'right': '0',
              'bottom': '0',
              'zIndex': '1',
              'backgroundColor': statusMap[status].bgc
            }).text(statusMap[status].text)
          })
        },
        statusRemove(id) {
          this.$nextTick(() => {
            $(`.myStatus_${id}`).remove()
          })
        },
        error(msg) {
          this.$notify({
            title: this.$t('错误'),
            message: msg,
            type: 'error',
            duration: 2000
          })
        },
        schange(value) {
          this.mainBodySelectValue = value
          // 校验是否需要展示出资人下拉. (dataRoom专属)
          this.loadingLpToDataRoom()
          // 选中后判断项目/基金..是否有对当前选中的目录有权限
          this.checkFolderPermission()
        },
        /** 上传结束后将文件传给父页面 */
        sendData() {
          // 不显示mianBody 不许要必填. mainBodyChoice 是显示类型 项目 基金
          if (this.mainBodyChoice === undefined || this.mainBodyChoice === '' || this.mainBodyChoice === null) {
            this.rules.mainBody = [{ required: false, message: '', trigger: 'blur' }]
          } else {
            // 显示mainBody组件,
            if (this.mainBodySelectValue !== '' && this.mainBodySelectValue !== undefined) {
              this.rules.mainBody = [{ required: false, message: '', trigger: 'blur' }]
            } else {
              this.rules.mainBody = [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
            }
          }
          this.$refs['form'].validate(valid => {
            // 验证数据
            if (valid) {
              // 表单中
              if (this.isShowFileType) {
                this.fileList.forEach(item => {
                  item.businessId = this.mainBodySelectValue
                  item.directoryId = this.folderId
                  item.directoryName = this.folderName
                  item.lpIdList = this.form.lpIdList
                })
              } else {
                // 文档库
                this.fileList.forEach(item => {
                  // 文件夹ID 交给文档库页面添加了
                  item.businessId = this.mainBodySelectValue
                  item.lpIdList = this.form.lpIdList
                })
              }
              const row = {
                fileList: this.fileList,
                form: this.form
              }
              // 给每个文件添加上提醒用户
              if (this.form.remindUsers !== '' && this.form.remindUsers !== null && this.form.remindUsers !== undefined && this.form.remindUsers.length > 0) {
                this.fileList.forEach(item => {
                  item.remindUsers = this.form.remindUsers.join(',')
                })
              }
              this.$emit('appendData', row)
              // this.$refs.uploader.fileList = []
              this.$set(this.$refs.uploader, 'fileList', [])
              this.$set(this.$refs.uploader.uploader, 'fileList', [])
              this.$parent.$parent.uploaderOpen = false
              // 关闭前将保存按钮重新设置为不可选中
              this.init()
            }
          })
        },
        /* *******************************  针对上传窗口中的数据加载等方法 ************************ */
        // 选择文件分类 文件夹
        currDeptChange(val) {
          // console.info('选择了: ', val)
          this.folderId = val.id
          this.folderName = val.name
          var belong = val.belong
          if (this.vueUploadCurrDeptChange !== undefined && this.vueUploadCurrDeptChange !== null && this.vueUploadCurrDeptChange.length > 0) {
            const object = this.vueUploadCurrDeptChange.find(obj => obj.busType === belong)
            if (object) {
              this.$nextTick(() => {
                this.selectBusType = object.busAlias
                // 项目类型. dealType....
                if (object.busOther !== '' && object.busOther !== null) {
                  this.mainBodyChoice = object.busOther
                }
                // console.log('belong:' + belong, 'this.selectBusType :' + this.selectBusType, 'this.mainBodyChoice:' + this.mainBodyChoice)
                this.$forceUpdate()
              })
            } else {
              this.mainBodyChoice = ''
              this.selectBusType = ''
            }
          } else {
            this.mainBodyChoice = ''
            this.selectBusType = ''
          }
        },
        /** 下拉加载 **/
        loadOptions({ action, parentNode, callback }) {
          if (action === 'LOAD_CHILDREN_OPTIONS') {
            // this.msgError('加载')
            this.currentBelong = parentNode.belong
            fileClassTreeStructure({ businessId: this.mainBodySelectValue, belong: parentNode.belong, parentId: parentNode.id }).then(response => {
              console.log(response)
              var data = response.data
              this.checkIfItIsOptionalMain(data)
              if (!this.isEmpty(data)) {
                parentNode.children = data
              } else {
                delete parentNode.children
                parentNode.hasChildren = false
              }
              callback()
            }).catch(() => {
              callback()
            })
          }
        },
        // 表单中上传时 加载文档类型
        directorySwitch() {
          console.log('加载文档类型')
          if (this.queryCount <= 0) {
            this.queryCount++
            this.loading = true
            // 按业务加载
            if (this.mainBodySelectValue !== '' && this.mainBodySelectValue !== undefined && this.mainBodySelectValue !== null) {
              // 根据businessId查出来该业务是基金还是项目还是其他
              this.elementLoadingText = this.$t('正在获取信息...')
              getLpView(this.mainBodySelectValue).then(responseLP => {
                this.queryCount = 0
                if (responseLP.data.length > 0) {
                  // 根据这个类型去除对应的项目目录
                  var type = responseLP.data[0].dealType
                  this.elementLoadingText = this.$t('正在加载特定文件类型...')
                  if (this.businessType === undefined || this.businessType === null || this.businessType === '') {
                    // 替换了上面注释内容
                    getArrayByCode('vueUpload_directorySwitch').then(response => {
                      const vueUploadDirectorySwitch = response.data
                      if (vueUploadDirectorySwitch !== undefined && vueUploadDirectorySwitch !== null && vueUploadDirectorySwitch !== '') {
                        const object = vueUploadDirectorySwitch.find(obj => obj.busType === type)
                        if (object) {
                          this.selectBusType = object.busType
                          // 项目类型. dealType....
                          if (object.busOther !== '' && object.busOther !== null) {
                            this.mainBodyChoice = object.busOther
                          }
                          type = object.busAlias
                        } else {
                          type = 'equity_deal'
                        }
                      } else {
                        type = 'equity_deal'
                      }
                      this.currentBelong = type
                      fileClassTreeStructure({ belong: type, businessId: this.mainBodySelectValue, parentId: '0' }).then(response => {
                        this.fileDirOptions = response.data
                        this.checkIfItIsOptionalMain(this.fileDirOptions)
                        this.loading = false
                      })
                    })
                  } else {
                    type = this.businessType
                    this.currentBelong = type
                    fileClassTreeStructure({ belong: type, businessId: this.mainBodySelectValue, parentId: '0' }).then(response => {
                      this.fileDirOptions = response.data
                      this.checkIfItIsOptionalMain(this.fileDirOptions)
                      this.loading = false
                    })
                  }
                } else {
                  this.loadingAllDir()
                }
              })
            } else {
              if (this.isShowFileType && this.uploadBusinessType !== undefined && this.uploadBusinessType !== null && this.uploadBusinessType !== '') {
                this.currentBelong = this.uploadBusinessType
                getArrayByCode('vueUpload_directorySwitch').then(response => {
                  const vueUploadDirectorySwitch = response.data
                  if (vueUploadDirectorySwitch !== undefined && vueUploadDirectorySwitch !== null && vueUploadDirectorySwitch !== '') {
                    const object = vueUploadDirectorySwitch.find(obj => obj.busType === this.uploadBusinessType)
                    if (object) {
                      this.selectBusType = object.busType
                      // 项目类型. dealType....
                      if (object.busOther !== '' && object.busOther !== null) {
                        this.mainBodyChoice = object.busOther
                      }
                      this.currentBelong = object.busAlias
                    }
                  }
                  fileClassTreeStructure({ belong: this.currentBelong, id: this.currentBelong, parentId: '0' }).then(response => {
                    this.fileDirOptions = response.data
                    this.checkIfItIsOptionalMain(this.fileDirOptions)
                    this.loading = false
                  })
                })
              } else {
                this.loadingAllDir()
              }
            }
          }
        },
        loadingAllDir() {
          // 加载全部文件夹
          this.elementLoadingText = this.$t('正在加载全部文件类型...')
          var belong = ''
          if (this.businessType !== '') {
            belong = this.businessType
          }
          this.currentBelong = belong
          getArrayByCode('vueUpload_directorySwitch').then(response => {
            const vueUploadDirectorySwitch = response.data
            if (!this.isEmpty(vueUploadDirectorySwitch)) {
              const object = vueUploadDirectorySwitch.find(obj => obj.busType === belong)
              if (object) {
                this.selectBusType = object.busType
                // 项目类型. dealType....
                if (object.busOther !== '' && object.busOther !== null) {
                  this.mainBodyChoice = object.busOther
                }
                this.currentBelong = object.busAlias
              }
            }
            fileClassTreeStructure({ belong: this.currentBelong, businessId: this.mainBodySelectValue, parentId: '0' }).then(response => {
              this.queryCount = 0
              this.fileDirOptions = response.data
              this.checkIfItIsOptionalMain(this.fileDirOptions)
              this.loading = false
            })
          })
        },
        // 检查是否可选
        checkIfItIsOptionalMain(data) {
          console.log('检查是否可选')
          this.expansionLevel = []
          if (!this.isEmpty(data) && data[0].parentId === '0') {
            var temp = []
            data.forEach(item => {
              temp.push(item.id)
            })
            this.$set(this, 'expansionLevel', temp)
          }
          data.forEach(item => {
            item.isDisabled = (item.isBuiltIn === '1' || item.fileLibraryRole.upload !== 'Y')
            this.checkIfItIsOptionalSub(item)
          })
        },
        checkIfItIsOptionalSub(data) {
          if (data !== null && data.children !== null) {
            data.children.forEach(item => {
              item.isDisabled = (item.isBuiltIn === '1' || item.fileLibraryRole.upload !== 'Y')
              this.checkIfItIsOptionalSub(item)
            })
          }
        },
        /**            文档库选择文件start              **/
        openFolderPageMethod() {
          this.openFolderPage = true
          this.$nextTick(() => {
            var selectIds = []
            if (this.selectFolderFiles) {
              this.selectFolderFiles.forEach(item => {
                selectIds.push(item.id)
              })
            }
            this.$refs.folderFastChioce.toggleSelectionIds = selectIds
          })
        },
        // 文档库选择相关
        uploadChoiceToParent(data, user) {
          this.openFolderPage = false
          this.$nextTick(() => {
            if (data) {
              data.forEach(item => {
                this.selectFolderFiles.push(item)
              })
              data.forEach(item => {
                const temp = {
                  id: item.id,
                  isFolder: false,
                  name: item.name,
                  size: this.calculateFileSize(item.sizes),
                  updateBy: { nickName: user.nickName },
                  createTime: new Date(),
                  dataType: this.dataType,
                  fileType: 'library',
                  tempSource: 'library'
                }
                this.selectChoiceFiles.push(temp)
                // 添加到fileList
                this.fileList.push(temp)
              })
            }
            this.saveBtnStatus()
          })
        },
        delFile(row, index) {
          this.selectChoiceFiles.splice(index, 1)
          if (this.selectFolderFiles) {
            this.selectFolderFiles.forEach((item, i) => {
              if (item.id === row.id) {
                this.selectFolderFiles.splice(i, 1)
              }
            })
          }
          if (this.fileList) {
            this.fileList.forEach((item, i) => {
              if (item.id === row.id) {
                this.fileList.splice(i, 1)
              }
            })
          }
        },
        /**
         * 判断保存按钮的状态
         */
        saveBtnStatus() {
          this.disabledSave = false
          this.fileList.forEach(item => {
            var uploadStatus = item.isUploading === undefined ? false : item.isUploading()
            if (uploadStatus && this.fileList.length > 0 && !this.disabledSave) {
              this.disabledSave = true
            }
          })
        },
        getUuid() {
          function S4() {
            return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
          }
          return (S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4())
        },
        // 计算文件大小  换算单位
        calculateFileSize(size) {
          size = parseInt(size)
          if (size > 0 && size < 1048576) {
            return (size / 1024).toFixed(2) + ' KB'
          } else if (size > 1048576) {
            return (size / 1024 / 1024).toFixed(2) + ' MB'
          } else {
            return ''
          }
        },
        /**
         * 由于上传组件比较深, 多判断几层
         * @returns {*}
         */
        getParentForm() {
          if (this.$parent.form !== undefined) {
            return this.$parent.form
          } else if (this.$parent.$parent.form !== undefined) {
            return this.$parent.$parent.form
          } else if (this.$parent.$parent.$parent.form !== undefined) {
            return this.$parent.$parent.$parent.form
          } else if (this.$parent.$parent.$parent.$parent.form !== undefined) {
            return this.$parent.$parent.$parent.$parent.form
          } else {
            return {}
          }
        },
        /**            文档库选择文件 end               **/
        // 加载dataRoom所需出资人
        loadingLpToDataRoom() {
          if (this.parentFolder.belong === 'data_room' && !this.isEmpty(this.mainBodySelectValue)) {
            // 获取所有的 LP用户
            listDict({ fundId: this.mainBodySelectValue }).then(response => {
              this.lpListOptions = response.data
            })
          }
        }
      }
    }
</script>
<style lang="scss" scoped>
/*.uploader-list /deep/ .uploader-file-actions>span {*/

/*去掉上传的暂停和回复按钮*/
.uploader-list /deep/ .uploader-file-actions .uploader-file-pause {
  display: none !important;
}

 .uploader-list /deep/ .uploader-file-actions .uploader-file-resume {
   display: none !important;
 }

/deep/ .el-form-item__content {
  margin: 0 !important;
  padding-right: 0 !important;
  clear: both;
}
/deep/ .uploader-file[status=error] .uploader-file-progress {
  background: #e2eeff !important;
}
/deep/ .uploader-drop {
  border: 0 dashed #ccc;
  background-color: #fff0;
}
.disableChoose {
  color: #d2d2d2;
}
</style>
